package com.jfs.health;

import cn.hutool.core.date.DateUtil;
import com.jfs.constant.CommonConstant;
import com.jfs.entity.Device;
import com.jfs.envent.EventPublisher;
import com.jfs.envent.entity.DeviceOfflineEventEntity;
import com.jfs.factory.SpringBeanFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;

/**
 * @Description 心跳任务检测实现类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
@Slf4j
public class HealthCheckTask implements BeatCheckTask{
    public HealthCheckTask(String deviceId, Integer heartBeatInterval) {
        this.deviceId = deviceId;
        this.heartBeatInterval = heartBeatInterval;
    }

    /**
     * 设备id
     */
    private String deviceId;
    /**
     * 任务开始时间
     */
    private long startTime;
    /**
     * 心跳周期
     */
    private long heartBeatInterval;


    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    @Override
    public void run() {
        try {
            //获取注册表中设备
            Device device = RegistryDevice.get(deviceId);
            if (Objects.isNull(device)) {
                log.error("心跳检测任务发生异常,设备不存在");
            } else {
                //判断设备状态
                Date keepaliveTime = device.getKeepaliveTime();
                long now = System.currentTimeMillis();
                if (log.isDebugEnabled()) {
                    log.debug("执行心跳检测,当前时间为:{},设备最后一次心跳时间:{}", DateUtil.date(now), keepaliveTime);
                }
                if (now - heartBeatInterval * 1000 > keepaliveTime.getTime()) {
                    device.setOnline(false);
                    RegistryDevice.registry(device);
                    //发布设备离线
                    EventPublisher eventPublisher = SpringBeanFactory.getBean(EventPublisher.class);
                    if (Objects.nonNull(eventPublisher)) {
                        DeviceOfflineEventEntity deviceOfflineEventEntity = new DeviceOfflineEventEntity(this);
                        deviceOfflineEventEntity.setDeviceID(device.getDeviceId());
                        deviceOfflineEventEntity.setIp(device.getIp());
                        deviceOfflineEventEntity.setPort(device.getPort());
                        eventPublisher.publish(deviceOfflineEventEntity);
                    }
                }
            }
        } catch (Exception e) {
            log.error("心跳检测逻辑发生异常:{}", e.getMessage());
            e.printStackTrace();
        }

    }

    @Override
    public String taskKey() {
        return CommonConstant.BEAT_TASK_KEY_PREFIX + deviceId;
    }
}
